﻿package com.aldoreyes.rpc.core 
{
	import com.aldoreyes.rpc.xml.XMLRPCRequestSerializer;
	import flash.events.ErrorEvent;
	import flash.events.Event;
	import flash.events.EventDispatcher;
	import flash.events.IOErrorEvent;
	import flash.net.URLLoader;
	import flash.xml.XMLDocument;
	
	/**
	 * ...
	 * @author Aldo Reyes
	 */
	public class RPCAsyncToken extends EventDispatcher
	{
		
		public static const RESULT_RECEIVED:String = "resultReceived";
		public static const RESULT_ERROR:String = "resultError";
		
		protected var data:*;
		
		public function RPCAsyncToken(loader:URLLoader) 
		{
			loader.addEventListener(IOErrorEvent.IO_ERROR, onError,false,0,true);
			loader.addEventListener(Event.COMPLETE, onResult,false,0,true);
		}
		
		protected function onError(e:IOErrorEvent):void {
			
		}
		
		protected function onResult(e:Event):void {
			try{
				data = XMLRPCRequestSerializer.deserialize(new XMLDocument(e.target.data));
				dispatchEvent(new Event(RESULT_RECEIVED));
			}catch (e:Error)
			{
				dispatchEvent(new ErrorEvent(ErrorEvent.ERROR, false, false, e.message));
			}
			
		}
	}
	
}